package com.yuexiao.service;


import com.alibaba.dubbo.config.annotation.Reference;
import com.yuexiao.config.RedisUtil;
import com.yuexiao.pojo.Employee;
import com.yuexiao.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ClassName:UserDetailsService
 * @Auther: YUEXIAO
 * @Description: 自定义用户登录权限
 * @Date: 2022/8/10 17:38
 * @Version: v1.0
 */
@Service("detailsService")
@Slf4j
public class DetailsService implements UserDetailsService {

    @Reference
    private UserService userService;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public UserDetails loadUserByUsername(String s) {
        log.info("手机号:{}",s);
        //从session中取出校验码
        Object str = redisUtil.get(s);
        if(str==null){
            throw new BadCredentialsException("验证码错误");
        }
        String checkcode= (String) str;

        //从数据库中查询用户是否存在
        User userByPhone = userService.getUserByPhone(s);
        if(userByPhone==null||userByPhone.getId()==null){
            throw new BadCredentialsException("用户不存在");
        }

        //将用户所具有权限存入权限集合
        List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_NOMAL");
        //返回security自带的User对象
        return new org.springframework.security.core.userdetails.User(userByPhone.getPhone(), checkcode, authorities);
    }
}
